package com.ly.web.controller.house;

import com.ly.base.ApiResponse;
import com.ly.base.RentValueBlock;
import com.ly.entity.SupportAddress;
import com.ly.service.IUserService;
import com.ly.service.ServiceMultiResult;
import com.ly.service.ServiceResult;
import com.ly.service.house.IAddressService;
import com.ly.service.house.IHouseService;
import com.ly.service.search.HouseBuketDTO;
import com.ly.service.search.ISearchService;
import com.ly.tast.updateIndex;
import com.ly.web.dto.*;
import com.ly.web.form.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 房源接口
 * @author ：LY
 * @date ：Created in 2020/11/10 15:53
 * @modified By：
 */
@Controller
public class HouseController {
    @Autowired
    private IAddressService addressService;

    @Autowired
    private IHouseService iHouseService;

    @Autowired
    private IUserService userService;

    @Autowired
    private ISearchService searchService;

    @Autowired
    private updateIndex updateIndex;

    /**
     * 方便用来用来更新索引,后续需要删除
     * @return
     */
    @GetMapping("update/all")
    @ResponseBody
    public ApiResponse updateall(){
        updateIndex.update();
        return ApiResponse.ofSuccess(ApiResponse.Status.SUCCESS);
    }

    /**
     * 自动补全提示接口
     * @param prefix
     * @return
     */
    @GetMapping("rent/house/autocomplete")
    @ResponseBody
    public ApiResponse autocomplete(@RequestParam(value = "prefix") String prefix){
      if (prefix.isEmpty()){
          return ApiResponse.ofStatus(ApiResponse.Status.BAD_REQUEST);
      }

        ServiceResult<List<String>> result = this.searchService.suggest(prefix);
        return ApiResponse.ofSuccess(result.getResult());
    }
    /**
     * 获取支持城市列表
     * @return
     */
    @GetMapping("address/support/cities")
    @ResponseBody
    public ApiResponse getSupportCities(){
        ServiceMultiResult<SupportAddressDTO> result = addressService.findAllCities();
        if (result.getResultSize() == 0){
            return ApiResponse.ofSuccess(ApiResponse.Status.NOT_FOUND);
        }
        return ApiResponse.ofSuccess(result.getResult());
    }

    /**
     * 获取对应城市支持区域列表
     * @param cityEnName
     * @return
     */
    @GetMapping("address/support/regions")
    @ResponseBody
    public ApiResponse getSupportRegions(@RequestParam(name = "city_name") String cityEnName){
        ServiceMultiResult<SupportAddressDTO> addressResult = addressService.findAllRegionsByCityName(cityEnName);
        if (addressResult.getResult() == null || addressResult.getTotal() <1){
            return  ApiResponse.ofStatus(ApiResponse.Status.NOT_FOUND);
        }
        return ApiResponse.ofSuccess(addressResult.getResult());
    }

    /**
     * 获取地铁线路信息
     * @param cityEnName
     * @return
     */
    @GetMapping("address/support/subway/line")
    @ResponseBody
    public ApiResponse getSupportSubwayLine(@RequestParam(name = "city_name") String cityEnName){
        List<SubwayDTO> subways = addressService.findAllSubwayByCity(cityEnName);
        if (subways.isEmpty()){
            return ApiResponse.ofStatus(ApiResponse.Status.NOT_FOUND);
        }
        return ApiResponse.ofSuccess(subways);
    }

    /**
     * 获取对应地铁线路所支持的地铁站点
     * @param subwayId
     * @return
     */
    @GetMapping("address/support/subway/station")
    @ResponseBody
    public ApiResponse getSupportSubwayStation(@RequestParam(name = "subway_id")Long subwayId){
       List<SubwayStationDTO> list = addressService.findAllStationBySubway(subwayId);
       if (list.isEmpty()){
           return ApiResponse.ofStatus(ApiResponse.Status.NOT_FOUND);
       }
        return ApiResponse.ofSuccess(list);
    }

    /**
     * 用户首页，必须选择城市，根据城市获取相应的房源信息
     * @param rentSearch
     * @param model
     * @param session
     * @param redirectAttributes
     * @return
     */
    @GetMapping("rent/house")
    public String rentHusePage(@ModelAttribute RentSearch rentSearch,
                               Model model, HttpSession session,
                               RedirectAttributes redirectAttributes){
        //查看传过来的参数是否包含城市英文缩写，包含则将它放到session中，不包含则在session中查看是否存在，都不存在则转发到首页
        if (rentSearch.getCityEnName() == null){
            String cityEnNameInSession = (String) session.getAttribute("cityEnName");
            if (cityEnNameInSession == null){
                redirectAttributes.addAttribute("msg","must_chose_city");
                return "redirect:/index";
            }else {
                rentSearch.setCityEnName(cityEnNameInSession);
            }
        }else{
            session.setAttribute("cityEnName",rentSearch.getCityEnName());
        }
        //通过城市英文缩写拿到城市详细数据
        ServiceResult<SupportAddressDTO> city = addressService.findCity(rentSearch.getCityEnName());
        if (!city.isSuccess()){
            redirectAttributes.addAttribute("msg","must_chose_city");
            return "redirect:/index";
        }

        //将结果进行数据绑定
        model.addAttribute("currentCity",city.getResult());
        //通过城市英文缩写获得所有地区信息
        ServiceMultiResult<SupportAddressDTO> addressResult = addressService.findAllRegionsByCityName(rentSearch.getCityEnName());
        if (addressResult.getResult() ==null || addressResult.getTotal() <1){
            redirectAttributes.addAttribute("msg", "must_chose_city");
            return "redirect:/index";
        }
        ServiceMultiResult<HouseDTO> sericeMultiResult = iHouseService.query(rentSearch);

        model.addAttribute("total",sericeMultiResult.getTotal());

        model.addAttribute("houses",sericeMultiResult.getResult());
        if (rentSearch.getRegionEnName() == null){
            rentSearch.setRegionEnName("*");
        }
        model.addAttribute("searchBody",rentSearch);
        model.addAttribute("regions",addressResult.getResult());

        model.addAttribute("priceBlocks", RentValueBlock.PRICE_BLOCK);
        model.addAttribute("areaBlocks",RentValueBlock.AREA_BLOCK);

        model.addAttribute("currentPriceBlock",RentValueBlock.matchPrice(rentSearch.getPriceBlock()));
        model.addAttribute("currentAreaBlock",RentValueBlock.matchArea(rentSearch.getAreaBlock()));

        return "rent-list";
    }

    /**
     * 用户界面房源详情信息展示  通过id获取房源信息，数据获取成功后绑定至Model上
     * @param houseId
     * @param model
     * @return
     */
    @GetMapping("rent/house/show/{id}")
    public String show(@PathVariable(value = "id") Long houseId,
                       Model model){
        if (houseId <=0 ){
            return "404";
        }
        ServiceResult<HouseDTO> serviceResult = iHouseService.findCompleteOne(houseId);
        if (!serviceResult.isSuccess()){
            return "404";
        }

        HouseDTO houseDTO = serviceResult.getResult();
        Map<SupportAddress.Level, SupportAddressDTO> addressMap = addressService.findCityAndRegion(houseDTO.getCityEnName(), houseDTO.getRegionEnName());

        SupportAddressDTO city = addressMap.get(SupportAddress.Level.CITY);
        SupportAddressDTO region = addressMap.get(SupportAddress.Level.REGION);

        model.addAttribute("city",city);
        model.addAttribute("region",region);
        ServiceResult<UserDTO> userDTOServiceResult = userService.findById(houseDTO.getAdminId());
        model.addAttribute("agent",userDTOServiceResult.getResult());
        model.addAttribute("house",houseDTO);

        ServiceResult<Long> result = searchService.aggregateDistrictHouse(city.getEnName(), region.getEnName(), houseDTO.getDistrict());
        //小区在售房源数量统计
        model.addAttribute("houseCountInDistrict",result.getResult());

        return "house-detail";
    }

    /**
     * 地图找房
     * @param cityEnName
     * @param model
     * @param session
     * @param redirectAttributes
     * @return
     */
    @GetMapping("rent/house/map")
    public String rentMapPage(@RequestParam(value = "cityEnName") String cityEnName,
                              Model model,
                              HttpSession session,
                              RedirectAttributes redirectAttributes){
       //查询城市是否合法
        ServiceResult<SupportAddressDTO> city = addressService.findCity(cityEnName);
        if (!city.isSuccess()){
            redirectAttributes.addAttribute("msg","must_chose_city");
            return "reirect:/index";
        }else {
            session.setAttribute("cityName",cityEnName);
            model.addAttribute("city",city.getResult());
        }
        ServiceMultiResult<SupportAddressDTO> regions = addressService.findAllRegionsByCityName(cityEnName);

        ServiceMultiResult<HouseBuketDTO> serviceMultiResult = searchService.mapAggregate(cityEnName);
        model.addAttribute("aggData",serviceMultiResult.getResult());
        model.addAttribute("total",serviceMultiResult.getTotal());
        model.addAttribute("regions",regions.getResult());
        return "rent-map";
    }


    /**
     * 获取地图上下左右经纬度范围内全部数据
     * @param mapSearch
     * @return
     */
    @GetMapping("rent/house/map/houses")
    @ResponseBody
    public ApiResponse rentMapHouse(@ModelAttribute MapSearch mapSearch){
        if (mapSearch.getCityEnName() == null){
            return ApiResponse.ofMessage(HttpStatus.BAD_REQUEST.value(),"必须选择城市");
        }
        ServiceMultiResult<HouseDTO> result;
        if (mapSearch.getLevel()<13){
            //全部查询
            result = iHouseService.wholeMapQuery(mapSearch);
        }else{
            //小地图查询必须传递地图边界的参数
            result= iHouseService.boundMapQuery(mapSearch);
        }

        ApiResponse response = ApiResponse.ofSuccess(result.getResult());
        response.setMore(result.getTotal()>(mapSearch.getStart()+mapSearch.getSize()));
        return response;
    }

    /**
     * 通过小区名和城市名获取房源信息
     * @param mapSearch
     * @return
     */
    @GetMapping("rent/house/map/houses/district")
    @ResponseBody
    public ApiResponse rentMapdistrict(@ModelAttribute MapSearchDistrict mapSearch){
        if (mapSearch.getCityEnName() == null){
            return ApiResponse.ofMessage(HttpStatus.BAD_REQUEST.value(),"必须选择城市");
        }
        ServiceMultiResult<HouseDTO> result ;
        //通过小区名与城市名获取到房源数据
        result = iHouseService.districtMapQuery(mapSearch);
        ApiResponse response = ApiResponse.ofSuccess(result.getResult());
        response.setMore(result.getTotal()>(mapSearch.getStart()+mapSearch.getSize()));
        return response;
    }

    /**
     * 已修改//通过地区获取此地区所有小区信息‘
     * 新方案：通过地图四个坐标获取所有小区数据
     * @param searchDistrict
     * @return
     */
    @GetMapping("/rent/house/map/district")
    @ResponseBody
    public ApiResponse rentMapDistrict(@ModelAttribute SearchDistrict searchDistrict){
        if (searchDistrict.getCityEnName() == null){
            return ApiResponse.ofMessage(HttpStatus.BAD_REQUEST.value(),"必须选择城市");
        }
        ServiceMultiResult<HouseBuketDTO> result = searchService.mapAggregateDistrict(searchDistrict);
        List<HouseBuketRegionDTO> res = new ArrayList<>();
       result.getResult().forEach(dto ->{
           res.add(new HouseBuketRegionDTO(dto.getKey(),iHouseService.findRegion(dto.getKey()).getMessage(), dto.getCount())); ;

       });

        ApiResponse response = ApiResponse.ofSuccess(res);
        return response;
    }
//    @GetMapping("/get")
//    @ResponseBody
//    public ApiResponse getregion(){
//        ServiceResult result = iHouseService.findRegion("融泽嘉园");
////        Map<String,HouseBuketDTO>
//        ApiResponse response = ApiResponse.ofSuccess(result.getMessage());
//        return response;
//    }

}
